<template>
  <div class="main-app">
    <el-row style="margin-top: 10px">
      <el-form ref="form" :model="form" :rules="rules" label-width="260px">
        <el-col :span="11">
          <el-form-item label="单位名称:" prop="name">
            <el-input v-model="form.name" :disabled="isEdit" />
          </el-form-item>
          <el-form-item label="地址:" prop="selectedOptions">
           <area-select type='text' v-if="infoloading"  v-model='form.selectedOptions' :data='$pcaa' :level='3' :disabled="isEdit"
             style="margin-left: -10px;margin-top: -1px; display: flex;line-height: 18px;"></area-select>

            <!-- <el-cascader v-model="form.selectedOptions" :options="options" style="width: 100%" :disabled="isEdit" /> -->
          </el-form-item>
          <el-form-item label="详细地址:">
            <el-input v-model="form.detailedAddress" :disabled="isEdit" />
          </el-form-item>
          <el-form-item label="年产废规模:" prop="awpsId">
            <el-select v-model="form.awpsId" placeholder="请选择年产废规模" style="width: 100%" :disabled="isEdit">
              <el-option v-for="item in awps" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="企业类型:" prop="enterpriseTypeId">
            <el-select v-model="form.enterpriseTypeId" placeholder="请选择企业类型" style="width: 100%" :disabled="isEdit">
              <el-option v-for="item in enterpriseCategory" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="环保负责人:" prop="epUserName">
            <el-input v-model="form.epUserName" clearable :disabled="isEdit" />
          </el-form-item>
          <el-form-item label="环保负责人电话:">
            <el-input v-model="form.epUserTel" clearable :disabled="isEdit" />
          </el-form-item>
          <el-form-item label="环保负责人手机号:" prop="epUserPhone">
            <el-input v-model="form.epUserPhone" clearable :disabled="isEdit" />
          </el-form-item>

          <!-- <el-form-item label="企业类别:" prop="enterpriseCategoryId">
            <el-select v-model="form.enterpriseCategoryId" multiple placeholder="请选择企业类别" style="width: 100%" :disabled="isEdit">
              <el-option v-for="item in enterpriseTypes" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item> -->

          <el-form-item label="经/纬度:">
            <el-col :span="7">
              <el-input v-model="form.longitude" placeholder="请输入经度" :disabled="isEdit" style="width: 100%;" />
            </el-col>
            <el-col class="line" :span="2">-</el-col>
            <el-col :span="7">
              <el-input v-model="form.latitude" placeholder="请输入纬度" :disabled="isEdit" />
            </el-col>

            <el-col :span="6">
              <el-button style="margin-left: 30px;" :disabled="isEdit" type="primary" icon="el-icon-place"
                @click="openDialog('经纬度详情')">
                点击设置
              </el-button>
            </el-col>

          </el-form-item>

        </el-col>
        <el-col :span="11">
          <el-form-item label="统一社会信用代码 (三证合一):" prop="unifiedSocialCreditCode">
            <el-input v-model="form.unifiedSocialCreditCode" :disabled="isEdit" />
          </el-form-item>
          <!-- <el-form-item v-if="!isEdit" label="三证合一附件 (营业执照图片）:"> -->
          <el-form-item v-if="!isEdit" label="三证合一附件 (营业执照图片）:">
            <el-upload action="" class="upload-demo" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
              :on-change="handleChangeLi" :auto-upload="false" :file-list="imageObjList">
              <el-button size="small" type="primary">点击添加</el-button>
            </el-upload>
          </el-form-item>

          <el-form-item v-else label="三证合一附件 (营业执照图片）:">
            <el-button type="primary" icon="el-icon-view" @click="
              ViewFile(
                '营业执照附件',
                `${form.businessLicensePictureUrlList}`
              )
            ">
              点击查看</el-button>
          </el-form-item>
          <el-form-item label="法定代表人:">
            <el-input v-model="form.legalRepresentativeName" clearable :disabled="isEdit" />
          </el-form-item>
          <el-form-item label="法定代表人电话:">
            <el-input v-model="form.legalRepresentativeTel" clearable :disabled="isEdit" />
          </el-form-item>
          <el-form-item label="法定代表人手机号:">
            <el-input v-model="form.legalRepresentativePhone" clearable :disabled="isEdit" />
          </el-form-item>
          <el-form-item label="总投资 (万):">
            <el-input v-model="form.totalInvestment" clearable :disabled="isEdit" />
          </el-form-item>
          <el-form-item label="邮政编码:">
            <el-input v-model="form.postalCode" clearable :disabled="isEdit" />
          </el-form-item>
          <el-form-item label="电子邮箱:">
            <el-input v-model="form.email" clearable :disabled="isEdit" />
          </el-form-item>

        </el-col>
      </el-form>
    </el-row>
    <el-row style="margin-top: 40px; text-align: center">
      <el-form :inline="true" class="form-inline">
        <el-form-item>
          <el-button v-show="!isEdit&&!isPublished" type="primary" @click="save(true)">保存草稿</el-button>
        </el-form-item>
        <el-form-item>
          <el-button v-show="!isEdit" type="primary" @click="save(false)">保存并提交</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <div class="dialog_diy">
      <el-dialog :visible.sync="dialogVisible" width="70%" style="margin-top: -100px" @close="closeDialog">
        <div slot="title" style="background: #1890ff; color: white">
          <div style="padding: 15px 20px">{{ picTitle }}</div>
        </div>
        <el-form ref="form" style="margin-top: 15px" :model="form">
          <div class="block">
            <el-carousel height="700px" style="text-align: center">
              <el-carousel-item v-for="item in urls" :key="item">
                <el-image style="height: 100%; width: 100%" fit="scale-down" :src="item" />
              </el-carousel-item>
            </el-carousel>
          </div>
          <el-row style="margin-top: 20px; text-align: center">
            <el-form :inline="true" class="form-inline">
              <el-form-item>
                <el-button @click="closeDialog">返 回</el-button>
              </el-form-item>
            </el-form>
          </el-row>
        </el-form>
      </el-dialog>

      <el-dialog :visible.sync="popup" width="70%" style="margin-top: -100px" @close="closeDialog">
        <div slot="title" style="background: #1890ff; color: white">
          <div style="padding: 15px 20px">{{ picTitle }}</div>
        </div>
        <el-form label-width="100px" style="margin-top: 20px;">
          <el-divider content-position="left">拖动红色表示获取位置经纬度信息</el-divider>
          <div class="block">
            <el-col :span="7">
              <el-form-item>
                <el-input v-model="keyWords" placeholder="请输入地区" style="width: 230px;margin-left: -50px;" />
                <el-button type="primary" style="margin-left: 20px;" :disabled="!keyWords" @click="setPlace">查询
                </el-button>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="当前经度:">
                <el-input v-model="longitude" :disabled="false" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="当前纬度:">
                <el-input v-model="latitude" :disabled="false" clearable />
              </el-form-item>
            </el-col>

            <div id="map" v-loading="loading" />
          </div>
          <el-row style="margin-top: 20px; text-align: center">
            <el-form :inline="true" class="form-inline">
              <el-form-item>
                <el-button type="danger" @click="initMap">重新定位</el-button>
                <el-button type="warning" @click="fixedPos_Here">获取当前定位</el-button>
                <el-button type="success" @click="btnSubmit">确认选择</el-button>
                <el-button @click="closeDialog">返 回</el-button>
              </el-form-item>
            </el-form>
          </el-row>
        </el-form>
      </el-dialog>
    </div>
    <!-- <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog> -->
  </div>
</template>

<script>
  import Vue from 'vue'
  import {
    pcaa
  } from 'area-data-vue';
  import 'area-linkage-vue/dist/index.css';

  import VueAreaLinkage from 'area-linkage-vue';

  Vue.prototype.$pcaa = pcaa;

  Vue.use(VueAreaLinkage);





  import {
    regionData,
    CodeToText,
    TextToCode
  } from "element-china-area-data";


  import {
    CompanyCategory,
    AnnualWasteProductionScale,
    CompanyType,
  } from "../../../utils/resource";
  import {
    save,
    updateCompanyImg,
    getEnterpriseById
  } from "../../../api/wastecomponey";

  import {
    NewGUID
  } from "../../../utils/index.js";

  export default {
    data() {
      const validateAddress = (rule, value, callback) => {
        if (this.form.selectedOptions.length === 0) {
          callback(new Error("请选择地址"));
        } else {
          callback();
        }
      };
      return {

        disabled: false,
        infoloading:true,

        options: pcaa,
        enterpriseTypes: CompanyCategory,
        awps: AnnualWasteProductionScale,
        enterpriseCategory: CompanyType,
        form: {
          name: "",
          detailedAddress: "",
          email: "",
          unifiedSocialCreditCode: "",
          companyLevel: "区县单位",
          enterpriseTypeId: "",
          epUserPhone: "",
          epUserTel: "",
          epUserName: "",
          awpsId: "",
          postalCode: "",
          totalInvestment: "",
          hwblNumber: "",
          legalRepresentativeTel: "",
          legalRepresentativePhone: "",
          selectedOptions: ["广西壮族自治区", "南宁市", "兴宁区", "民生街道"],
          legalRepresentativeName: "",
          dialogImageUrl: "",
          latitude: "",
          longitude: "",
          // isAdd: '1', //新增为1，修改为0
        },

        id: "",
        isEdit: false,
        isPublished: false,

        // 上传图片用
        picFile: {
          id: '',
          file: [],
          type: "1",
          name: "",
          uid: "",
          isDel: "0" // 0表示新增，1表示删除
        },
        imageObjList: [],
        imageObjList_Del: [],
        fileList: [
          //   {
          //   name: 'food.jpeg',
          //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?food.jpeg'
          // },
        ],
        urls: [
          // "https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg",
        ],
        picTitle: "图片详情",
        dialogVisible: false,

        // 获取经纬度相关
        popup: false,
        map: null,
        local: null,
        mk: null,
        latitude: '',
        longitude: '',
        keyWords: '',
        loading: false,

        rules: {
          epUserName: [{
            required: true,
            message: "请输入环保负责人",
            trigger: "blur",
          }],
          epUserPhone: [{
            required: true,
            message: "请输入环保负责人手机号",
            trigger: "blur",
          }],
          name: [{
            required: true,
            message: "请输入单位名称",
            trigger: "blur",
          }],
          selectedOptions: [{
            type: "array",
            required: true,
            validator: validateAddress,
          }],
          enterpriseTypeId: [{
            required: true,
            message: "请选择企业类型",
            trigger: "change",
          }],

          unifiedSocialCreditCode: [{
            required: true,
            message: "请选择统一社会信用代码",
            trigger: "change",
          }],
          businessLicensePictureUrl: [{
            required: true,
            message: "请选择三证合一附件",
            trigger: "change",
          }],
          awpsId: [{
            required: true,
            message: "请选择年产废规模",
            trigger: "change",
          }],
        },

        isDisable: false, // 第三方变量进行防重,
      };
    },
    async mounted() {
      this.$refs["form"].resetFields();
      const {
        id,
        isEdit
      } = this.$route.params;
      if (isEdit === "false") {
        this.isEdit = true;
      } else {
        this.isEdit = false;
      }
      this.id = id;
      if(id){
        this.infoloading=false;
      }
      await this.getEnterpriseById(id);
    },

    methods: {

      /**
       * 文件上传删除
       */
      handleRemove(file, fileList) {
        var obj = this.imageObjList.findIndex(item => {
          return item.uid === file.uid
        });
        if (obj >= 0) {
          if (this.imageObjList[obj].file) {
            this.imageObjList.splice(obj, 1);
          } else {
            this.imageObjList[obj].isDel = "1"; // 如果没有文件内容，说明此文件是从云上下载的
            this.imageObjList_Del.push(this.imageObjList[obj]);
            this.imageObjList.splice(obj, 1);
          }
        }
      },

      /**
       * 文件发生改变时
       */
      handleChangeLi(file, fileList) {
        var obj = {
          id: "",
          file: file.raw,
          type: "1", // 更新类型 (1: 营业执照图片，2: 道路运输许可证图片)
          name: file.name,
          uid: file.uid,
          isDel: "0"
        }
        this.imageObjList.push(obj);
      },
      handlePictureCardPreview(file) {},

      async getEnterpriseById(id) {

        const {
          data
        } = await getEnterpriseById(id, "0");
        this.form.name = data.name;
        // this.form.selectedOptions.push(TextToCode[data.province].code);
        // this.form.selectedOptions.push(TextToCode[data.province][data.city].code);
        // this.form.selectedOptions.push(
        //   TextToCode[data.province][data.city][data.area].code
        // );
        this.form.selectedOptions = [];
        this.$set( this.form.selectedOptions, 0,data.province);
         this.$set( this.form.selectedOptions, 1,data.city);
          this.$set( this.form.selectedOptions, 2,data.area);
           this.$set( this.form.selectedOptions, 3,data.street);
           this.infoloading=true;
     
        this.form.detailedAddress = data.detailedAddress;
        this.form.email = data.email;
        this.form.epUserName = data.epUserName;
        this.form.epUserPhone = data.epUserPhone;
        this.form.epUserTel = data.epUserTel;
        // this.form.enterpriseCategoryId = data.enterpriseCategoryId.split(",");
        this.form.enterpriseTypeId = data.enterpriseTypeId;
        this.form.unifiedSocialCreditCode = data.unifiedSocialCreditCode;
        this.form.awpsId = data.awpsId;
        // this.form.hwblNumber = data.hwblNumber;
        this.form.latitude = data.latitude != null ? data.latitude.toString() : '';
        this.form.longitude = data.longitude != null ? data.longitude.toString() : '';

        this.form.postalCode = data.postalCode;
        this.form.totalInvestment = data.totalInvestment != null ? data.totalInvestment.toString() : '';
        this.form.legalRepresentativeName = data.legalRepresentativeName;
        this.form.legalRepresentativeTel = data.legalRepresentativeTel;
        this.form.legalRepresentativePhone = data.legalRepresentativePhone;
        this.form.businessLicensePictureUrlList = data.businessLicensePictureUrlList;
        this.form.companyLevel = data.companyLevel != null ? data.companyLevel.toString() : '区县单位';
        if (data.isPublish === 1) {
          this.isPublished = true;
        }

        if (this.form.businessLicensePictureUrlList) {
          this.imageObjList = [];
          this.form.businessLicensePictureUrlList.forEach(item => {
            var List = item.split("/");
            var nameList = List[List.length - 1].split('?');
            var obj = {
              id: id,
              file: '',
              type: "1", // 更新类型 (1: 营业执照图片，2: 道路运输许可证图片)
              name: nameList[1],
              uid: nameList[0].split(".")[0],
              url: item,
              isDel: "0"
            }
            this.imageObjList.push(obj);
          })
        }

      },
      async ViewFile(title, url) {
        this.picTitle = title;
        this.urls = url.split(",");
        this.dialogVisible = true;
      },
      closeDialog() {
        this.dialogVisible = false;
        this.popup = false;
      },

      async save(value) {



        this.$refs["form"].validate(async (valid) => {
          if (valid) {
            // 全局使用，使用和关闭加载页面
            this.$axios.startLoading();
            var thisID = "";
            const formData = new FormData();
            for (const key in this.form) {
              formData.append(key, this.form[key]);
            }
            let message = "";
            var isAdd = "1";
            if (!this.id) {
              message = "产废单位新增成功";
              thisID = NewGUID();
              formData.append("id", thisID);

              isAdd = "1";
            } else {
              thisID = this.id;
              formData.append("id", this.id);
              isAdd = "0";
              message = "产废单位修改成功";
            }
            formData.delete("province");
            formData.delete("city");
            formData.delete("area");
            if (value) {
              formData.append("isPublish", '0');
            } else {

              if (CodeToText[this.form.selectedOptions[2]] == "市辖区") {
                // 全局使用，使用和关闭加载页面
                this.$axios.closeLoading();
                this.$notify({
                  title: "失败",
                  message: "当前所选县（区）【市辖区】信息无效！",
                  type: "error",
                  duration: 3000,
                });
                return
              }

              formData.append("isPublish", '1');
            }

            formData.append("type", "20");
            // formData.append("province", CodeToText[this.form.selectedOptions[0]]);
            // formData.append("city", CodeToText[this.form.selectedOptions[1]]);
            // formData.append("area", CodeToText[this.form.selectedOptions[2]]);

            formData.append("province", this.form.selectedOptions[0]);
            formData.append("city", this.form.selectedOptions[1]);
            formData.append("area", this.form.selectedOptions[2]);
            formData.append("street", this.form.selectedOptions[3]);
            formData.append("latitude", this.form.latitude.toString());
            formData.append("longitude", this.form.longitude.toString());
            formData.append("disabled", "0");

            formData.append("isAdd", isAdd);

            await save(formData);

            var imageFileList = [];
            this.imageObjList.forEach(item => {
              imageFileList.push(item);
            })
            this.imageObjList_Del.forEach(item => {
              imageFileList.push(item);
            })

            await this.updateCompanyImg(imageFileList, thisID);

            // 全局使用，使用和关闭加载页面
            this.$axios.closeLoading();

            this.$notify({
              title: "成功",
              message: message,
              type: "success",
              duration: 3000,
            });
            this.$router.push("/organization/wasteproduction");
          } else {
            return false;
          }
        });
      },

      async updateCompanyImg(imageFileList, guid) {
        for (let i = 0; i < imageFileList.length; i++) {
          const imageFormData = new FormData();
          imageFormData.append('id', guid);
          imageFormData.append('type', imageFileList[i].type);
          imageFormData.append('file', imageFileList[i].file);

          imageFormData.append('name', imageFileList[i].name);
          imageFormData.append('uid', imageFileList[i].uid);
          imageFormData.append('isDel', imageFileList[i].isDel);

          await updateCompanyImg(imageFormData);
        }
      },

      cancel() {
        this.$router.push("/organization/wasteproduction");
      },

      // 获取经纬度
      // 打开弹窗，name为弹窗名称
      async openDialog(name) {
        this.picTitle = name;
        this.popup = true;

        this.initMap();
      },
      // 确认
      btnSubmit() {
        this.form.latitude = this.latitude;
        this.form.longitude = this.longitude

        this.popup = false;
      },
      initMap() {
        this.latitude = this.form.latitude;
        this.longitude = this.form.longitude;

        this.$nextTick(() => {
          this.map = new BMap.Map("map");
          const point = new BMap.Point(this.form.longitude, this.form.latitude);
          this.map.centerAndZoom(point, 12);
          this.map.enableScrollWheelZoom(true); // 开启鼠标滚轮缩放
          this.map.addControl(new BMap.NavigationControl());

          this.fixedPos(point);
        });
      },

      fixedPos_Here() {
        this.fixedPos();
      },

      // 点击定位-定位到当前位置
      fixedPos(point) {
        const _this = this;
        const geolocation = new BMap.Geolocation();
        if (point.lat) { // 初次定位
          _this.handleMarker(_this, point);
        } else {
          _this.loading = true;
          geolocation.getCurrentPosition(function(r) {
            if (this.getStatus() === BMAP_STATUS_SUCCESS) {
              _this.handleMarker(_this, r.point);
              const myGeo = new BMap.Geocoder();
              myGeo.getLocation(new BMap.Point(r.point.lng, r.point.lat),
                function(result) {
                  _this.loading = false;
                  if (result) {
                    _this.latitude = result.point.lat;
                    _this.longitude = result.point.lng;
                  }
                }
              );
            } else {
              _this.loading = false;
              _this.$message.error("failed" + this.getStatus());
            }
          });
        }
      },
      // 搜索地址
      setPlace() {
        this.loading = true;
        this.local = new BMap.LocalSearch(this.map, {
          onSearchComplete: this.searchPlace,
        });
        this.loading = false;
        this.local.search(this.keyWords);
      },
      searchPlace() {
        if (this.local.getResults() !== undefined) {
          this.map.clearOverlays(); // 清除地图上所有覆盖物

          if (this.local.getResults().getPoi(0)) {
            const point = this.local.getResults().getPoi(0).point; // 获取第一个智能搜索的结果
            this.map.centerAndZoom(point, 18);
            this.handleMarker(this, point);
            // console.log("经度：" + point.lng + "--" + "纬度" + point.lat);
            this.latitude = point.lat;
            this.longitude = point.lng;
          } else {
            this.$message.error("未匹配到地点!");
          }
        } else {
          this.$message.error("未找到搜索结果!");
        }
      },
      // 设置标注
      handleMarker(obj, point) {
        const that = this;
        obj.mk = new BMap.Marker(point);
        obj.map.addOverlay(obj.mk);
        obj.mk.enableDragging(); // 可拖拽
        obj.mk.addEventListener("dragend", function(e) {
          // 监听标注的拖拽，获取拖拽后的经纬度
          that.latitude = e.point.lat;
          that.longitude = e.point.lng;
        });
        obj.map.panTo(point);
      },

    },
  };
</script>
<style lang="scss" scoped>
  .dialog_diy {
    ::v-deep .el-dialog__wrapper {

      // eslint-disable-line
      .el-dialog {
        .el-dialog__body {
          padding: 0px;
        }

        .el-dialog__header {
          padding: 0px;
        }

        .el-dialog__headerbtn {
          top: 5px;
          right: 5px;
          padding-top: 10px;
        }

        .el-dialog__headerbtn .el-dialog__close {
          color: #fff;
          height: 30px;
          width: 35px;
        }

        .el-dialog__headerbtn .el-dialog__close:hover {
          color: gray;
        }
      }
    }
  }
</style>

<style scoped>
  .form-layer {
    width: 100%;
  }

  #map {
    margin-top: 30px;
    margin-left: 2%;
    width: 96%;
    height: 600px;
    border: 1px solid gray;
    box-sizing: border-box;
    overflow: hidden;
  }

  /deep/ .el-dialog {
    min-width: 550px;
  }

  /deep/ .el-dialog__body {
    padding: 10px;
  }
</style>
